package com.wanfajie.smsdistribute.db.repository.impl

import com.j256.ormlite.dao.Dao
import com.wanfajie.smsdistribute.db.helper.PhoneDatabaseHelper
import com.wanfajie.smsdistribute.db.bean.phone.PhoneGroup
import com.wanfajie.smsdistribute.db.quietInvoke
import com.wanfajie.smsdistribute.db.repository.GroupRepository
import java.sql.SQLException

object GroupRepositoryImpl: GroupRepository {
    private val TAG = javaClass.simpleName

    private val dao: Dao<PhoneGroup, Int> = PhoneDatabaseHelper.getDao(PhoneGroup::class.java)!!

    override fun saveGroup(group: PhoneGroup) : Boolean {
        return quietInvoke(TAG, false, SQLException::class) {
            dao.create(group) == 1
        }
    }

    override fun removeGroup(group: PhoneGroup): Boolean {
        return quietInvoke(TAG, false, SQLException::class) {
            group.phoneNumbers?.clear()
            println(group.phoneNumbers)
            dao.delete(group) == 1
        }
    }

    override fun removeGroup(id: Int): Boolean {
        return quietInvoke(TAG, false, SQLException::class) {
            dao.deleteById(id) == 1
        }
    }


    override fun getGroups(): List<PhoneGroup> {
        return quietInvoke(TAG, emptyList(), SQLException::class) {
            dao.queryBuilder()
                    .selectRaw()
                    .orderBy(PhoneGroup.ID, false)
                    .query()
        }
    }

    override fun updateGroup(group: PhoneGroup): Boolean {
        return quietInvoke(TAG, false, SQLException::class) {
            dao.update(group) == 1
        }
    }

    override fun findById(id: Int): PhoneGroup? {

        return quietInvoke(TAG, SQLException::class) {
            dao.queryForId(id)
        }
    }

    override fun has(id: Int): Boolean {
        return quietInvoke(TAG, false, SQLException::class) {
            dao.idExists(id)
        }
    }

    override fun hasName(name: String): Boolean {
        return quietInvoke(TAG, false, SQLException::class) {
            dao.queryForEq(PhoneGroup.GROUP_NAME_FIELD, name).isNotEmpty()
        }
    }
}